package com.fausto.learnimprint.mail

import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.mail.javamail.JavaMailSenderImpl
import java.util.*

@Configuration
class MailSenderConfig {

    @Value("\${spring.mail.host}")
    lateinit var mailHost: String

    @Value("\${spring.mail.port}")
    lateinit var mailPort: String

    @Value("\${spring.mail.username}")
    lateinit var mailUsername: String

    @Value("\${spring.mail.password}")
    lateinit var mailPassword: String

    @Bean
    fun javaMailSender(): JavaMailSenderImpl {
        return JavaMailSenderImpl().apply {
            this.host = mailHost
            this.port = mailPort.toInt()
            this.username = mailUsername
            this.password = mailPassword

            this.javaMailProperties = Properties().let {
                it["mail.smtp.auth"] = "true"
                it["mail.smtp.starttls.enable"] = "true"
                it["mail.required"] = "true"
                it["mail.smtp.socketFactory.port"] = "465"
                //it["mail.smtp.ssl.enable"] = "true"
                it["mail.smtp.socketFactory.class"] = "javax.net.ssl.SSLSocketFactory"
                it["mail.smtp.socketFactory.fallback"] = "false"

                it
            }
        }
    }
}